package org.xshop.core.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.xshop.core.interceptor.SignInterceptor;

import top.ibase4j.core.config.WebMvcConfig;
import top.ibase4j.core.filter.TokenFilter;
import top.ibase4j.core.interceptor.BaseInterceptor;
import top.ibase4j.core.interceptor.EventInterceptor;
import top.ibase4j.core.interceptor.MaliciousRequestInterceptor;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.PropertiesUtil;

/**
 * @author ShenHuaJie
 * @since 2018年4月21日 下午2:46:54
 */
@Configuration
@ComponentScan("org.xshop.web")
public class WebConfig extends WebMvcConfig {

    @Override
    public BaseInterceptor eventInterceptor() {
        return new EventInterceptor();
    }

    @Bean
    public FilterRegistrationBean<TokenFilter> tokenFilterRegistration() {
        FilterRegistrationBean<TokenFilter> registration = new FilterRegistrationBean<TokenFilter>(new TokenFilter());
        registration.setName("tokenFilter");
        registration.addUrlPatterns("/*");
        registration.setOrder(5);
        return registration;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        MaliciousRequestInterceptor requestInterceptor = new MaliciousRequestInterceptor();
        if (DataUtil.isNotEmpty(PropertiesUtil.getInt("request.minInterval"))) {
            requestInterceptor.setMinRequestIntervalTime(PropertiesUtil.getInt("request.minInterval"));
        }
        requestInterceptor.setNextInterceptor(eventInterceptor(), new SignInterceptor());
        registry.addInterceptor(requestInterceptor).addPathPatterns("/**").excludePathPatterns("/*.ico", "/*/api-docs",
            "/swagger**", "/swagger-resources/**", "/webjars/**", "/configuration/**");
    }
}
